<template>
  <el-dialog class="formdrawer" :title="'修改结果'" v-model="visible">
    <!--  表单内容 -->
    <el-form
      class="formstyle"
      :model="form"
      ref="dataFormRef"
      :rules="rules"
      label-position="right"
      label-width="120px"
      @submit.prevent
    >
      <el-form-item label="旧结果">
        <el-input v-model="oldResult" :style="{ width: '500px' }" disabled />
      </el-form-item>
      <el-form-item label="新结果" prop="result">
        <el-input v-model="form.result" :style="{ width: '500px' }" />
      </el-form-item>
    </el-form>

    <!-- 底部的确认、取消按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancleBtn">{{ "取消" }}</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">
          {{ "确定" }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { apiupdateOrderQalnfo } from "@/api/tasksheet";
import emitter from "@/utils/eventbus"; //引入bus

// 定义变量内容
const visible = ref(false);
const loading = ref(false);
const dataFormRef = ref(); // form表单的ref

// 提交表单数据
const form = reactive({
  id: "",
  order_no: "",
  result: "",
  checker: "",
});
// 清空表单
const clearForm = () => {
  form.id = "";
  form.order_no = "";
  form.result = "";
  form.checker = "";
};
// 校验规则
const rules = {
  result: [
    {
      required: true,
      // pattern: /^(-?\d+(\.\d+)?)$/,
      message: "新结果不可为空",
    },
  ],
};
const oldResult = ref();
// 打开弹窗
const openDialog = (row: any, value: string) => {
  // console.log("openDialog", row);
  // 清空表单
  clearForm();
  visible.value = true; // 打开弹窗
  // 重置表单数据---否则新增弹窗会自动触发校验
  nextTick(() => {
    dataFormRef.value?.resetFields();
    form.id = row.id;
    form.order_no = row.order_no;
    form.checker = row.checker;
    oldResult.value = value; //旧
  });
};

// 提交表单
const onSubmit = async () => {
  // 表单校验
  const valid = await dataFormRef.value.validate().catch(() => {});
  if (!valid) return false;

  try {
    loading.value = true;

    await apiupdateOrderQalnfo([form])
      .then((res: any) => {
        if (res.code == 200) {
          // 提示框
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          emitter.emit("refreshQa"); //调用父组件刷新方法
        } else {
          ElMessage({
            message: res.msg,
            type: "error",
          });
        }
      })
      .catch((err) => {
        ElMessage.error(err.message);
      });

    visible.value = false;
  } catch (err: any) {
    ElMessage.error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 取消按钮
const cancleBtn = () => {
  visible.value = false;
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped lang="scss">
.formstyle {
  padding: 0 80px;
}
</style>
